package com.summer.user.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.primefaces.model.UploadedFile;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.summer.core.annotations.Logger;
import com.summer.core.annotations.ScopeType;
import com.summer.core.controller.LoginUserInfo;
import com.summer.core.util.FacesUtil;
import com.summer.core.util.IdGenerator;
import com.summer.user.model.Official;


@Scope(ScopeType.VIEW)
@Component
public class OfficialHome {
	
	private UploadedFile file;
	
	@Logger
	static Log log;
	
	@Resource
	HibernateTemplate ht;
	@Resource
	LoginUserInfo loginUserInfo;

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String importExcel() {

		if (file == null) {
			FacesUtil.addErrorMessage("未发现上传的文件！请先上传文件后，再导入表格！");
			return null;
		}
		InputStream is;
		try {
			
			is = file.getInputstream(); // 文件流
			Workbook wbs = WorkbookFactory.create(is);
			Sheet sheet = wbs.getSheetAt(0);
			int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
			List<Official> list = new ArrayList<Official>();
			// 遍历每一行
			for (int r = 2; r < rowCount; r++) {
				log.info("开始整第"+r+"条记录");
				XSSFRow row = (XSSFRow) sheet.getRow(r);
				/** 总列数 */
				int cellCount = sheet.getRow(0).getPhysicalNumberOfCells(); // 获取总列数
				// 遍历每一列
				Official o = null;
				if(r > 0) {
					o = new Official();
					o.setId(IdGenerator.randomUUID());
				}
				for (int c = 0; c < cellCount; c++) {
					Cell cell = row.getCell(c);
					cell.setCellType(1);
					/** 单元格 */
					String cellValue = getValue(cell);
					if(o != null) {
						setValues(o, c, cellValue);
					}
				}
				if(o != null) {
					o.setUploader(loginUserInfo.getLoginUser());
					o.setUpload_time(new Date());
					list.add(o);
					log.info("第"+ r +"条数据为：" + o);
				}
				System.out.println();
			}
			if(list != null && list.size() > 0) {
				ht.saveOrUpdateAll(list);
			}
			FacesUtil.addInfoMessage("文件上传成功！请检查上传结果！");
		} catch (Exception e) {
			e.printStackTrace();
			FacesUtil.addErrorMessage("批量导入失败！请检查上传结果！");
		}
		return FacesUtil.redirect("/admin/official/officialList");
	}
	
	private String getValue(Cell cell) {
		int cellType = cell.getCellType();
		String cellValue = null;
		switch (cellType) {
		case Cell.CELL_TYPE_STRING: // 文本
			cellValue = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_NUMERIC: // 数字、日期
			if (DateUtil.isCellDateFormatted(cell)) {
				cellValue = String.valueOf(cell.getNumericCellValue()); // 日期型
			} else {
				cellValue = String.valueOf(cell.getNumericCellValue()); // 数字
			}
			break;
		case Cell.CELL_TYPE_BOOLEAN: // 布尔型
			cellValue = String.valueOf(cell.getBooleanCellValue());
			break;
		case Cell.CELL_TYPE_BLANK: // 空白
			cellValue = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_ERROR: // 错误
			cellValue = "错误";
			break;
		case Cell.CELL_TYPE_FORMULA: // 公式
			cellValue = "错误";
			break;
		default:
			cellValue = "错误";
		}
		return cellValue;
	}
	
	public void setValues(Official o, int c, String value) {
		try {
			String prop=getMethodName().get(c);
			String methodName="set"+prop.substring(0, 1).toUpperCase() + prop.substring(1);
			Object val = value;
			Class clazz=String.class;
			if(prop.equals("offer_count")) {
				clazz = Integer.class;
				String regEx="[^0-9]";  
				Pattern p = Pattern.compile(regEx);  
				Matcher m = p.matcher(val.toString());
				val = Integer.parseInt(m.replaceAll("").trim());
			}
			o.getClass().getMethod(methodName, new Class[]{clazz}).invoke(o, new Object[]{val});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Map<Integer, String> getMethodName() {
//		Method m = Official.class.getMethod(str, new Class[]{String.class}).invoke(movingInvokeTest, new Object[]{"s"});
		Map<Integer, String> map = new HashMap<Integer, String>();
		map.put(0, "department_name");
		map.put(1, "position_name");
		map.put(2, "department_code");
		map.put(3, "post_code");
		map.put(4, "subject_type");
		map.put(5, "test_area");
		map.put(6, "offer_count");
		map.put(7, "recruit_target");
		map.put(8, "education");
		map.put(9, "degree");
		map.put(10, "degree_allow");
		map.put(11, "major");
		map.put(12, "sex");
		map.put(13, "political_face");
		map.put(14, "min_service_year");
		map.put(15, "work_experience");
		map.put(16, "pe_test");
		map.put(17, "department_level");
		map.put(18, "department_nature");
		map.put(19, "pe_standard");
		map.put(20, "hotline");
		map.put(21, "remark");
		return map;
	}
	
	
	public UploadedFile getFile() {
		return file;
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}
	
	public static void main(String[] args) {
		OfficialHome home = new OfficialHome();
		Official o = new Official();
		home.setValues(o, 1, "abc");
		System.out.println(o);
	}
}
